<template>
  <app-page card full>
    <!-- <template #header>
      <el-radio-group v-model="pageData.query.systemType">
        <el-radio-button
          :label="item.value"
          v-for="(item, index) in stores.dict.systemType"
          :key="index"
          @change="pageActions.handleSearch()"
        >
          {{ item.label }}
        </el-radio-button>
      </el-radio-group>
    </template> -->

    <app-page-main>
      <template #header>
        <div class="app-query"></div>
        <div class="app-action">
          <el-button type="primary" plain icon="plus" @click="pageActions.handleAdd()">添加</el-button>
        </div>
      </template>

      <el-tabs v-model="pageData.query.systemType" @tab-change="handleTabClick" v-if="stores.dict">
        <el-tab-pane
          :label="item.label"
          :name="item.value"
          v-for="(item, index) in stores.dict.systemType"
          :key="index"
        ></el-tab-pane>
      </el-tabs>

      <el-table
        v-loading="pageData.loading"
        :data="pageData.data"
        stripe
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <el-table-column label="菜单名称" width="220">
          <template #default="scope">{{ scope.row.menuName }}</template>
        </el-table-column>
        <el-table-column label="类型">
          <template #default="scope">{{ scope.row.typeDesc }}</template>
        </el-table-column>
        <el-table-column label="权限标识">
          <template #default="scope">{{ scope.row.authKey }}</template>
        </el-table-column>
        <el-table-column label="图标">
          <template #default="scope">
            <i :class="scope.row.icon"></i>
          </template>
        </el-table-column>
        <el-table-column prop="rank" label="排序" show-overflow-tooltip></el-table-column>
        <el-table-column prop="path" label="路径" show-overflow-tooltip></el-table-column>
        <el-table-column label="菜单状态">
          <template #default="scope">
            <el-switch
              :before-change="
                () =>
                  pageActions.handleUpdate(
                    scope.row,
                    { isOpen: !scope.row.isOpen },
                    !scope.row.isOpen ? '确认上线？' : '确认下线？',
                    '已修改'
                  )
              "
              v-model="scope.row.isOpen"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              icon="plus"
              @click="pageActions.handleAdd({ parentId: row.id, systemType: row.systemType })"
            >
              新增
            </el-button>
            <el-button link type="primary" icon="edit" @click="pageActions.handleEdit(row)">修改</el-button>
            <el-button link type="primary" icon="copyDocument" @click="handleCopy(row)"> 复制 </el-button>
            <el-button link type="primary" icon="delete" @click="pageActions.handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </app-page-main>

    <!-- 新增/编辑 -->
    <jax-dialog-edit
      width="640px"
      v-model="pageData.detail"
      v-model:show="pageData.shwoEdit"
      :json="formJson"
      @submit="handleSubmit"
      :id-key="pageData.key"
      type="drawer"
      size="768px"
      labelWidth='85px'
    >
      <ApiEdit v-model="pageData.detail.apis" />
      <WebPathEdit v-model="pageData.detail.paths" />
    </jax-dialog-edit>
  </app-page>
</template>

<script setup>
import { ElMessageBox, ElMessage } from 'element-plus'
import { usePageList, useAppStore, useMenuStore, http } from 'jax-node'

import ApiEdit from './components/ApiEdit.vue'
import WebPathEdit from './components/WebPathEdit.vue'

const { query } = useRoute()
const stores = useAppStore()
const menuStore = useMenuStore()

const { pageData, pageActions } = usePageList({
  // api: '/system/menu',
  // key: 'id',
  query: {
    systemType: query.systemType || 'admin',
  },
  defaultDetail: {
    type: 0,
    isHide: false,
    isOpen: true,
    apis: [],
    paths: [],
  },
})

const menuList = ref([])

pageActions.getData = () => {
  getMenuTree()
  getMenuList()
}

pageActions.handleBeforeSubmit = detail => {
  detail.systemType = pageData.query.systemType
}

const formJson = computed(() => {
  const fixed = false
  const required = true

  return [
    { name: 'rank', label: '序号', type: 'inputNumber', tips: '（序号越小越靠前）' },

    { name: 'menuName', label: '菜单名称', required: true },
    {
      name: 'parentId',
      label: '上级菜单',
      type: 'select',
      options: menuList.value,
      placeholder: '选择上级菜单',
      inputAttr: { style: 'width:100%' },
    },

    {
      name: 'type',
      label: '类型',
      type: 'radioGroup',
      options: [
        { label: '页面', value: 0 },
        { label: '按钮', value: 1 },
        { label: '外链', value: 2 },
      ],
    },

    (() => {
      let json = []

      if ([0, 2].includes(pageData.detail.type)) {
        json = [
          { name: 'path', label: '菜单路径' },
          { name: 'icon', label: '菜单图标' },
        ]
      }

      return json
    })(),

    [{ name: 'authKey', label: '权限标识' }],
    [
      {
        name: 'isHide',
        label: '隐藏',
        type: 'radioGroup',
        options: [
          { label: '否', value: false },
          { label: '是', value: true },
        ],
      },
      // {
      //   name: 'isExternal',
      //   label: '外链',
      //   type: 'radioGroup',
      //   options: [
      //     { label: '否', value: false },
      //     { label: '是', value: true },
      //   ],
      // },
    ],
  ]
})

const handleTabClick = (tab, event) => pageActions.handleSearch()
const handleSubmit = () => {
  pageActions.handleSubmit().then(() => {
    menuStore.getMenu()
  })
}

// 获取菜单树
function getMenuTree() {
  http(`/system/menu/tree`, {
    params: {
      systemType: pageData.query.systemType,
    },
  }).then(res => {
    pageData.data = res
  })
}

// 获取菜单列表
function getMenuList() {
  http(`/system/menu`, {
    params: {
      systemType: pageData.query.systemType,
    },
  }).then(res => {
    menuList.value = res.map(item => {
      let prefix = ''
      if (item.index > 1) {
        prefix = '├' + '─'.repeat((item.index - 1) * 1)
      }
      return {
        ...item,
        label: prefix + item.menuName,
        value: item.id,
        index: item.index,
      }
    })
  })
}

const handleCopy = item => {
  ElMessageBox.confirm('确认复制?', '提示', {
    type: 'warning',
  }).then(() => {
    http
      .post(`${pageData.api}/copy`, {
        id: item.id,
        renames: ['menuName'],
      })
      .then(() => {
        ElMessage.success('复制成功')
        pageActions.refresh()
      })
  })
}
</script>

<style lang="scss" scoped></style>
